<?php
   // ************************************************************************
   // **                                                                    **
   // **          This original software was designed and coded by          **
   // **                                                                    **
   // **                         David A. Goldsmith                         **
   // **                                                                    **
   // **                       dave106@wonderdave.com                       **
   // **                                                                    **
   // **                          March/April 2005                          **
   // **                         Revised April 2008                         **
   // **                       Revised September 2008                       **
   // **            Revised for Galileo High School, August 2009            **
   // **                                             July   2010            **
   // **                       piperd@galileoweb.org                        **	
   // **                                                                    **
   // ************************************************************************
?>


<html>
<title>Computer Lab Signup System</title>


<?php
   include("Configure.php");

    function globalz() {
        // Define and initialize global variables
        global $Date, $Room, $User;
    }
    globalz();

    $Date     =  mysql_real_escape_string($_POST['Date']);
    $Room     =  mysql_real_escape_string($_POST['Room']);
    $User     =  mysql_real_escape_string($_POST['User']);

    if (isset($_POST['Lab']))
    {
      $Lab   =  mysql_real_escape_string($_POST['Lab']);
    }
    else
        $Lab = 0;
    if (isset($_POST['Reserve1']))
    {
      $Reserve1   =  mysql_real_escape_string($_POST['Reserve1']);
      $Reserve2   =  mysql_real_escape_string($_POST['Reserve2']);
    }
    else
        $Reserve1 = 0;
     if (isset($_POST['Cancel1']))
    {
      $Cancel1   =  mysql_real_escape_string($_POST['Cancel1']);
      $Cancel2   =  mysql_real_escape_string($_POST['Cancel2']);
    }
    else
        $Cancel1 = 0;

   // Set up a "hidden" form that can be used to call the file Logout.php to log out the teacher
   echo "<form name='LogoutForm' method='post' action='Logout.php'>";
   echo "<input type='hidden' name='User' value='$User'>";
   echo "</form>";

   // Make sure this file is not being called manually by a user (without a username) or from an unauthorized
   //  file or location (on a different server)
   $PageFrom = $_SERVER["HTTP_REFERER"];
   $BadCall = 0;

   if ((! $User) or (($PageFrom != $URL_01) and ($PageFrom != $URL_03)))
      $BadCall = 1;
   else
   {
      // Make sure the teacher has an active session
      $Query = mysql_query("SELECT Username FROM LabSessions WHERE Username='$User'", $DB);
      $NumRecords = mysql_num_rows($Query);
      if ($NumRecords == 0)
         $BadCall = 1;

      // Make sure the teacher's session did not start before today and has not been inactive for more than
      //  $IDLE_TIME minutes today
      $Query = mysql_query("SELECT Username FROM LabSessions
                            WHERE (Username='$User') AND
                                  (((CURDATE()=Date) AND (DATE_SUB(NOW(), INTERVAL $IDLE_TIME MINUTE) > Time)) OR
                                   (CURDATE()>Date))", $DB);
      $NumRecords = 0;
      if ($Query)
         $NumRecords = mysql_num_rows($Query);
      if ($NumRecords > 0)
         $BadCall = 1;
   }

   if ($BadCall == 1)
   {
      //echo "<body bgcolor='#000000' onLoad='document.LogoutForm.submit()'>";
      //exit();
   }
?>


<head>
   <meta http-equiv="Robots" content="none, noarchive">
   <meta http-equiv="Cache-Control" content="no-cache">
   <meta http-equiv="Pragma" content="no-cache">
   <meta http-equiv="Expires" content="-1">
   <?php
      $TempIdle = $IDLE_TIME * 60;
      $DateTime = getdate();
      if ($DateTime['hours'] == 23)
         $TempIdle = $TempIdle - ($DateTime['minutes'] * 60 + $DateTime['seconds']);
      echo "<meta http-equiv=\"Refresh\" content=\"$TempIdle; url=javascript:document.LogoutForm.submit()\">\n";
   ?>
</head>

<link rel="stylesheet" href="LAB-Teacher.css" type="text/css">
<body onContextMenu="return false" onDragStart="return false" onSelectStart="return false">


<?php
   function CellColor($Teacher)
   {
      global $User;

      if (! $Teacher) { return "#8fbc8f"; }
      if ($Teacher == $User) { return "#6495ed"; }
      if (($Teacher != $User) && ($Teacher)) { return "#fa8072"; }
   }

   function FirstName($Teacher)
   {
      global $DB;

      $Query = mysql_query("SELECT FirstName FROM LabTeachers WHERE Username='$Teacher'", $DB);
      $Data = mysql_fetch_array($Query);

      if ($Data["FirstName"]) { return $Data["FirstName"]; }
      if ($Teacher) { return ""; }
      return "[ Lab";
   }

   function LastName($Teacher)
   {
      global $DB;

      $Query = mysql_query("SELECT LastName FROM LabTeachers WHERE Username='$Teacher'", $DB);
      $Data = mysql_fetch_array($Query);

      if ($Data["LastName"]) { return $Data["LastName"]; }
      if ($Teacher) { return $Teacher; }
      return "Available ]";
   }

   function SetupCell($Teacher, $Period, $Info, $Height)
   {
      global $User, $Superuser, $CellCount, $Room, $Date, $Day;

      $CellColor = CellColor($Teacher);
      $FullName = FirstName($Teacher) . " " . LastName($Teacher);
      $CellCount++;

      echo "<form name='Form$CellCount' method='post' action='DisplayWeek.php'>";
      echo "<input type='hidden' name='User' value='$User'>";
      echo "<input type='hidden' name='Room' value='$Room'>";
      echo "<input type='hidden' name='Date' value='$Date'>";

      // Display the period and section times in a cell, along with the teacher (if any) who has reserved the lab
      echo "<tr bgcolor='$CellColor'>";
      echo "<td valign=top align=center><table border=0 cellpadding=0 cellspacing=0>";
      echo "<tr><td valign=top align=center>$Info</td></tr>";
      echo "<tr><td valign=center align=center height=$Height>$FullName</td></tr>";
      echo "<tr><td valign=bottom align=center>";

      // If the day being shown has not already passed, display a "Cancel" button for the current user
      if (($Teacher == $User) or (($Superuser == "Y") and ($Teacher)))
      {
         if ($Day >= date("Y-m-d"))
         {
            echo "<input type='hidden' name='Cancel1' value='$Day'>";
            echo "<input type='hidden' name='Cancel2' value='$Period'>";
            echo "<a href='javascript:document.Form$CellCount.submit()'>";
            echo "<img src='Button-Cancel.gif' width=70 height=13 border=0></a>";
         }
         else
            echo "<img src='Image-TransparentDot.gif' width=1 height=13 border=0>";
      }

      // If the day being shown has not already passed, display a "Reserve" button for the current user
      if (! $Teacher)
      {
         if ($Day >= date("Y-m-d"))
         {
            echo "<input type='hidden' name='Reserve1' value='$Day'>";
            echo "<input type='hidden' name='Reserve2' value='$Period'>";
            echo "<a href='javascript:document.Form$CellCount.submit()'>";
            echo "<img src='Button-Reserve.gif' width=70 height=13 border=0></a>";
         }
         else
            echo "<img src='Image-TransparentDot.gif' width=1 height=13 border=0>";
      }

      // Since the lab is not available for the day/period being shown, do not display any buttons
      if (($Teacher != $User) and ($Teacher))
         echo "<img src='Image-TransparentDot.gif' width=1 height=13 border=0>";

      echo "</td></tr></table>";
      echo "</td></tr></form>";
   }

    $Suffix = str_replace(" ", "_", $Room); 

   // Check to see if the teacher has JUST submitted a request to RESERVE a lab for a class period
   if ($Reserve1)
   {
      // Only allow the teacher to reserve the lab and class period if they are still available; it's possible that
      //  in the time between when the teacher first displayed the weekly schedule on his/her screen and when the
      //  teacher actually clicked on the "RESERVE" button, another teacher may have reserved that lab and time slot    
      $Query = mysql_query("UPDATE LabSignups$Suffix SET Signup$Reserve2='$User'
                            WHERE Date='$Reserve1' AND Signup$Reserve2=''", $DB);
   }


   // Check to see if the teacher has JUST submitted a request to CANCEL a lab for a class period
   if ($Cancel1)
      $Query = mysql_query("UPDATE LabSignups$Suffix SET Signup$Cancel2='' WHERE Date='$Cancel1'", $DB);


   // In case the teacher has switched to a different lab, make sure the correct weekly schedule is displayed
   if ($Lab)
      $Room = $Lab;
   $Lab = $Room;

   $Suffix = str_replace(" ", "_", $Room); 


   // Determine if the teacher is a superuser
   $Query = mysql_query("SELECT Superuser FROM LabTeachers WHERE Username='$User'", $DB);
   $Data = mysql_fetch_array($Query);
   $Superuser = $Data["Superuser"];


   // Display a heading at the top of the page containing the room number of the lab for which the schedule is being shown
   echo "<table align=center width=700 border=0 cellpadding=0 cellspacing=0><tr>";
   echo "<td width=128><font face='Arial' size=5 color='#000000'><b>$Room</b></font></td>";


   // Retrieve all of the computer labs from the "Labs" table
   $Query = mysql_query("SELECT Room FROM Labs ORDER BY Room", $DB);
   $NumLabs = mysql_num_rows($Query);

   // Display a pulldown menu that allows the teacher to select a lab schedule to display
   echo "<form name='LabForm' method='post' action='DisplayWeek.php'>";
   echo "<input type='hidden' name='User' value='$User'>";
   echo "<input type='hidden' name='Room' value='$Room'>";
   echo "<input type='hidden' name='Date' value='$Date'>";
   echo "<td><font face='Arial' size=2 color='#000000'><b>Change Lab:</b></font> &nbsp;";

   echo "<select name='Lab' onChange='submit()'>";
   while ($Data = mysql_fetch_array($Query))
   {
      $TempRoom = $Data["Room"];
      if ($Lab == "$TempRoom")
         echo "<option selected>$TempRoom";
      else
         echo "<option>$TempRoom";
   }
   echo "</select></td></form>";

  
   // Display a "Logout" button
   echo "<form><td align=right width=124>";
   echo "<input type='button' value='Logout' style='width:80px;color:#000000;font-weight:bold' ";
   echo "onClick='document.LogoutForm.submit()'></td>";
   echo "</td></form>";
   echo "</tr></table><br>";


   echo "<table align=center border=3 cellpadding=0 cellspacing=0 bordercolor='#800080'><tr>";

   $CellCount = 0;
   for ($CounterA=0; $CounterA<=4; $CounterA++)
   {
      // Advance to the next day of the week
      $Day = date("Y-m-d", mktime(0, 0, 0, date("m", strtotime($Date)),
                                           date("d", strtotime($Date)) + $CounterA,
                                           date("Y", strtotime($Date))));

      // Retrieve the lab signup information from the "LabSignups" table for lab $Room for the day being processed
      $Query1 = mysql_query("SELECT * FROM LabSignups$Suffix WHERE Date='$Day'", $DB);
      $Data1 = mysql_fetch_array($Query1);

      $Schedule = $Data1["Schedule"];
      $ShowDay = date("F j, Y", strtotime($Day));
      $Weekday = date("l", strtotime($Day));

      echo "<td><table height=472 border=1 cellpadding=2 cellspacing=0 bordercolor='#800080'>";

      // Retrieve the information about the type of day being processed from the "LabDayTypes" table
      $Query2 = mysql_query("SELECT * FROM LabDayTypes WHERE Schedule='$Schedule'", $DB);
      $Data2 = mysql_fetch_array($Query2);

      echo "<tr valign=top bgcolor='#000000'><th width=140 height=54>$Weekday<br>$ShowDay<br>";
      echo "<font color='#ffff00'>$Schedule</font></th></tr>";

      // Determine the number of periods in the day being processed
      $NumPeriods = 0;
      for ($Counter=1; $Counter<=8; $Counter++)
         if ($Data2["Info$Counter"])
            $NumPeriods++;

      // Determine the height of the "name" part of each period cell in the table for the day being processed
      $TotalHeight = 416 - (34 * $NumPeriods);
      $NumBigCells = $TotalHeight % $NumPeriods;
      if ($NumPeriods > 0) { $CellHeight = ceil($TotalHeight / $NumPeriods); }

      // Display the lab signup information for the day being processed
      for ($CounterB=1; $CounterB<=$NumPeriods; $CounterB++)
      {
         if (($CounterB == $NumBigCells + 1) and ($NumBigCells > 0))
            $CellHeight--;
         SetupCell($Data1["Signup$CounterB"], $CounterB, $Data2["Info$CounterB"], $CellHeight);
      }

      echo "</table></td>";
   }

   echo "</tr></table><br>";


   // Determine the date of the Monday for this current week (or for the upcoming week, if it is now a weekend)
   $ThisFriday = date("Y-m-d 00:00:00", strtotime("this Friday"));
   $Monday = date("Y-m-d", strtotime("last Monday", strtotime($ThisFriday)));


   // Determine the date of the Monday for the most recent viewable week that is earlier than the week of $Date,
   //  but not earlier than the week of $Monday (if such a week exists in the "LabSignups" table for lab $Room),
   //  unless the teacher is a superuser, in which case he/she should be allowed to view existing weeks that have
   //  already passed
   if ($Superuser == "Y")
      $Query = mysql_query("SELECT Date FROM LabSignups$Suffix
                            WHERE (Date<'$Date') AND (DAYOFWEEK(Date)=2) ORDER BY Date DESC", $DB);
   else
      $Query = mysql_query("SELECT Date FROM LabSignups$Suffix
                            WHERE (Date<'$Date') AND (Date>='$Monday') AND (DAYOFWEEK(Date)=2)
                            ORDER BY Date DESC", $DB);
   $Data = mysql_fetch_array($Query);
   $LastWeek = $Data["Date"];
   $NumRecords1 = mysql_num_rows($Query);


   // Determine the date of the Monday for the earliest viewable week that is later than the week of $Date (if
   //  such a week exists in the "LabSignups" table for lab $Room)
   $Query = mysql_query("SELECT Date FROM LabSignups$Suffix
                         WHERE (Date>'$Date') AND (DAYOFWEEK(Date)=2)
                         ORDER BY Date", $DB);
   $Data = mysql_fetch_array($Query);
   $NextWeek = $Data["Date"];
   $NumRecords2 = mysql_num_rows($Query);


   // Display the "Last Week" and "Next Week" buttons, if appropriate
   echo "<table align=center border=0 cellpadding=0 cellspacing=0><tr>";

   if ($NumRecords1 > 0)
   {
      echo "<form method='post' action='DisplayWeek.php'><td>";
      echo "<input type='hidden' name='User' value='$User'>";
      echo "<input type='hidden' name='Room' value='$Room'>";
      echo "<input type='hidden' name='Date' value='$LastWeek'>";
      echo "<input type='submit' value='<--- &nbsp; &nbsp; Last Week' ";
      echo "style='width:132px;color:#000000;font-weight:normal'></td>";
      echo "</td></form>";
   }

   if (($NumRecords1 > 0) and ($NumRecords2 > 0))
      echo "<td width=25></td>";

   if ($NumRecords2 > 0)
   {
      echo "<form method='post' action='DisplayWeek.php'><td>";
      echo "<input type='hidden' name='User' value='$User'>";
      echo "<input type='hidden' name='Room' value='$Room'>";
      echo "<input type='hidden' name='Date' value='$NextWeek'>";
      echo "<input type='submit' value='Next Week &nbsp; &nbsp; --->' ";
      echo "style='width:132px;color:#000000;font-weight:normal'></td>";
      echo "</td></form>";
   }

   echo "</tr></table><br>";


   // Display a brief description of the computer lab for which the schedule is being shown
   $Query = mysql_query("SELECT Description FROM Labs WHERE Room='$Room'", $DB);
   $Data = mysql_fetch_array($Query);
   $Description = $Data["Description"];

   echo "<center><font face='Arial' size=2 color='#000000'><b>$Description</b></font></center>";


   // Since the teacher has just performed an action, update the "Time" field in the appropriate row of
   //  the "LabSessions" table
   $Query = mysql_query("UPDATE LabSessions SET Time=NOW() WHERE Username='$User'", $DB);
?>


<script language="JavaScript" type="text/javascript">
   // The following function is called whenver a key is pressed; if the key is a numeral (0 - 9) greater than zero
   //  and less than or equal to the current number of computer labs, the corresponding lab will be displayed (1 =
   //  the first lab, 2 = the second lab, etc.); note that this code MUST occur AFTER the code that sets the value
   //  of the PHP variable $NumLabs
   function CheckLabKey(Key, NumLabs)
   {
      KeyPressed = (isNS) ? Key.which : event.keyCode;
      KeyPressed -= 48;
      if ((KeyPressed >= 1) && (KeyPressed <= <?php echo $NumLabs ?>))
      {
         document.LabForm.Lab.selectedIndex = KeyPressed - 1;
         document.LabForm.submit();
      }
   }

   var isNS = (navigator.appName == "Netscape");
   document.onkeydown = CheckLabKey;
   if (isNS) { document.captureEvents(Event.KEYDOWN); }
</script>


</body>

</html>
